package com.wang.test.demo.putong;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangzhenjun
 * @date 2022/3/10 16:21
 */
public class FinalizeEscapeGC {

    public static FinalizeEscapeGC SAVE_HOOK = null;
    public void isAlive() {
        System.out.println("yes, i am still alive :)");
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize method executed!");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }
    public static void main(String[] args) throws Throwable {
        test();
        SAVE_HOOK = new FinalizeEscapeGC();
//对象第一次成功拯救自己
        SAVE_HOOK = null;
        System.gc();
// 因为Finalizer方法优先级很低，暂停0.5秒，以等待它
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, i am dead :(");
        }
//// 下面这段代码与上面的完全相同，但是这次自救却失败了SAVE_HOOK = null;
//        System.gc();
//// 因为Finalizer方法优先级很低，暂停0.5秒，以等待它
//        Thread.sleep(500);
//        if (SAVE_HOOK != null) {
//            SAVE_HOOK.isAlive();
//        } else {
//            System.out.println("no, i am dead :(");
//        }
    }
    public static void test(){
        List<String> a = new ArrayList<String>();
        List<String> b = new ArrayList<String>();
        List<String> c = new ArrayList<String>();
        List<String> d = new ArrayList<String>();

        a.add("a");
        a.add("b");
        a.add("c");

        b.add("b");
        b.add("c");
        b.add("d");

        a.removeAll(b);

        System.out.println(a);
        System.out.println(b);

    }

}
